package msg

import (
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/cheneylau/components/web-server/global"
	"github.com/astaxie/beego/httplib"
	"strings"
	"time"
)

func GetQWechatAccessTokenString(appSecretName string) (string, error) {
	cacheKey := fmt.Sprintf("QWechatAccessToken_%s",appSecretName)
	obj := global.MemoryCache.Get(cacheKey)
	if obj != nil {
		cToken := obj.(*StorageToken)
		if cToken != nil && time.Now().Before(cToken.EndTime) {
			return cToken.Token, nil
		}
	}
	fmt.Println("request qwechat accessToken...")
	res, err := GetQWechatAccessToken(appSecretName)
	if err != nil {
		return "", err
	}

	if res.Errcode != 0 {
		return "", errors.New(res.Errmsg)
	}
	token := StorageToken{
		Token:     res.AccessToken,
		StartTime: time.Now(),
		EndTime:   time.Now().Add(time.Second * time.Duration(res.ExpiresIn)),
		ExpiresIn: res.ExpiresIn,
	}
	global.MemoryCache.Put(cacheKey, &token, time.Second*time.Duration(res.ExpiresIn))
	return res.AccessToken, nil
}

func SendMsgToQYUserWithBuzHelper(markdownMsg string, qyUid int64) error {
	qAccessToken, err := GetQWechatAccessTokenString("buz_helper_et_wechat_corpsecret")
	if err != nil {
		return err
	}
	//发送消息
	params := make(map[string]interface{})
	url := "https://qyapi.weixin.qq.com/cgi-bin/message/send"
	params["touser"] =  fmt.Sprintf("%v|", qyUid)
	params["msgtype"] = "markdown"
	params["agentid"] = "1000048"
	params["safe"] = 0
	params["enable_id_trans"] = 0
	params["enable_duplicate_check"] = 0
	params["duplicate_check_interval"] = 0
	markdown := make(map[string]interface{})
	markdown["content"] = markdownMsg
	params["markdown"] = markdown
	wxres, err := WXSendRequest(url, params, qAccessToken, "post")
	if err != nil {
		return err
	}

	if len(wxres.Errmsg) == 0 {
		fmt.Println("消息发送成功!")
	}

	return nil
}

func WXSendRequest(url string, params map[string]interface{}, accessToken string, method string) (*WXRes, error) {
	if strings.ToLower(method) == "post" {
		req := httplib.Post(url + "?" + "access_token=" + accessToken)
		req.JSONBody(params)
		s, err := req.String()
		if err != nil {
			return nil, err
		}
		//fmt.Println("请求结果为:" + s)
		//Log("wechat-api", s)
		var apiRes WXRes
		err = json.Unmarshal([]byte(s), &apiRes)
		if err != nil {
			return nil, err
		}
		return &apiRes, nil
	} else if strings.ToLower(method) == "get" {
		req := httplib.Get(url + "?" + "access_token=" + accessToken)
		for key, value := range params {
			req.Param(key, fmt.Sprintf("%v", value))
		}
		s, err := req.String()
		if err != nil {
			return nil, err
		}
		//fmt.Println("请求结果为:" + s)
		//Log("wechat-api", s)
		var apiRes WXRes
		err = json.Unmarshal([]byte(s), &apiRes)
		if err != nil {
			return nil, err
		}
		return &apiRes, nil
	}

	return nil, nil
}

type WXRes struct {
	Errcode     int           `json:"errcode"`
	Errmsg      string        `json:"errmsg"`
	AccessToken string        `json:"access_token"`
	ExpiresIn   int           `json:"expires_in"`
	Msgid       string         `json:"msgid"`
	Userlist    []QWUser 	  `json:"userlist"`
}

type QWUser struct {
	Userid     string `json:"userid"`
	Name       string `json:"name"`
	Department []int  `json:"department"`
	Position   string `json:"position"`
	Mobile     string `json:"mobile"`
	Gender     string `json:"gender"`
	Email      string `json:"email"`
	Avatar     string `json:"avatar"`
	Status     int    `json:"status"`
	Enable     int    `json:"enable"`
	Isleader   int    `json:"isleader"`
	Extattr struct {
		Attrs []interface{} `json:"attrs"`
	} `json:"extattr"`
	HideMobile     int     `json:"hide_mobile"`
	EnglishName    string  `json:"english_name"`
	Telephone      string  `json:"telephone"`
	Order          []int64 `json:"order"`
	MainDepartment int     `json:"main_department"`
	QrCode         string  `json:"qr_code"`
	Alias          string  `json:"alias"`
	IsLeaderInDept []int   `json:"is_leader_in_dept"`
	ThumbAvatar    string  `json:"thumb_avatar"`
	ExternalProfile struct {
		ExternalAttr     []interface{} `json:"external_attr"`
		ExternalCorpName string        `json:"external_corp_name"`
	} `json:"external_profile,omitempty"`
	Address string `json:"address,omitempty"`
}

type StorageToken struct {
	Token     string
	StartTime time.Time
	ExpiresIn int
	EndTime   time.Time
}

func GetQWechatAccessToken(appSecretName string) (*WXRes, error) {
	req := httplib.Get("https://qyapi.weixin.qq.com/cgi-bin/gettoken")
	req.Param("corpid", "wx045d055c4e7bab5e")
	req.Param("corpsecret", "bu7Iz7C1LP_9BeBlNeDHY4Bt9DcNgGFhPT5QECha7zM")
	res, err := req.String()
	if err != nil {
		return nil, err
	}
	var apiRes WXRes
	err = json.Unmarshal([]byte(res), &apiRes)
	if err != nil {
		return nil, err
	}

	return &apiRes, nil
}
